package org.jeecg.modules.product.test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 使用 CountDownLatch 实现多线程计数
 * CountDownLatch 是一个同步辅助类，允许一个或多个线程等待其他线程完成操作。
 */
public class CounterWithCountDownLatch {
    private final AtomicInteger count = new AtomicInteger(0);
    private final CountDownLatch latch = new CountDownLatch(2);  // 等待2个线程完成

    public void increment() {
        count.incrementAndGet();  // 原子操作，无需加锁
    }

    public int getCount() {
        return count.get();
    }

    public static void main(String[] args) throws InterruptedException {
        CounterWithCountDownLatch counter = new CounterWithCountDownLatch();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
            counter.latch.countDown();  // 线程完成任务后，计数器减1
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();

        counter.latch.await();  // 主线程等待所有线程完成任务

        System.out.println("Final count: " + counter.getCount()); // 输出应该是2000
    }
}